tax.controller('importVatCtrl',function($scope,$http,$stateParams,$compile){

  $scope.vat = {
    vatNumber:null,  // 发票号码
    remarks: null,  //备注
    vatUser: null, //开票人
    receiverUser: null,//收票人
    checkUser:null,//复核人
    userId: null,//登记人
    type:null,  //0是进销发票 ，1是出销发票
    photoAdress:null,//照片上传地址
    price:0,
    allPrice:0,
    vatMoney:0,
    inCompany: {  // 供货商
      companyId:null,
      companyName:null,
      companyNumber:null,
      companyAddress:null,
      companyPhone:null,
      companyAccount:null,
      bank:null
    },
    outCompany: {
      companyId:null,
      companyName:null,
      companyNumber:null,
      companyAddress:null,
      companyPhone:null,
      companyAccount:null,
      bank:null
    },
    listData: []
  };

  /******* 通过Excel表格文件导入数据 start *************/
  $scope.importModel = false;
  $scope.importData = function(){
    $scope.importModel = !$scope.importModel;
  }
  $scope.sureImport = function() {
    $scope.importBtn = true;
    var formdata = new FormData(document.getElementById("excleform"));
    var xhr = new XMLHttpRequest();
	    xhr.onload=function(event)
	    {
	      if  ( ( xhr.status >= 200 && xhr.status < 300) || xhr.status == 304)   //上传成功

	      {
          $scope.importBtn = false;
					var response = JSON.parse(xhr.response);
					alertMes(response.serviceResult,response.resultInfo);
					if(response.serviceResult){
            $(".closeImport").click();
					}
	      }
	      else
	      {
	        alertMes(false,"批量导入失败");
          $scope.importBtn = false;
	      }
	    };
			xhr.open("POST", excelURL,true);
			xhr.send(formdata);
  }
  /******* 通过Excel表格文件导入数据 end *************/

  // 清空发票表格数据
  $scope.clearVat = function(){
    $scope.vat = {
      vatNumber:null,  // 发票号码
      remarks: null,  //备注
      vatUser: null, //开票人
      receiverUser: null,//收票人
      checkUser:null,//复核人
      userId: null,//登记人
      type:null,  //0是进销发票 ，1是出销发票
      photoAdress:null,//照片上传地址
      price:null,
      allPrice:null,
      vatMoney:null,
      inCompany: {  // 供货商
        companyId:null,
        companyName:null,
        companyNumber:null,
        companyAddress:null,
        companyPhone:null,
        companyAccount:null
      },
      outCompany: {
        companyId:null,
        companyName:null,
        companyNumber:null,
        companyAddress:null,
        companyPhone:null,
        companyAccount:null
      },
      listData: []
    };
  }

  /******* 单条发票数据添加 start *************/
  //录入单条信息
  $scope.addRecordBtn = false;
  $scope.addRecord = function(){
    $scope.addRecordBtn = true;
    $scope.vat.vatDate = $("#id-date-picker-1").val();
    $scope.vat.userId = sessionStorage.userId;
    $http.post(addCommodityURL,$scope.vat)
    .success(function(res){
      alertMes(res.serviceResult,res.resultInfo);
      if (res.serviceResult) {
        $scope.clearVat();
      }
    })
    .error(function(){
      alertMes("noHttp",null);
    });
  }
  $scope.addPhoto = function(){
    var formdata = new FormData();
    formdata.append('file', $('#photoFile')[0].files[0]);
    var xhr = new XMLHttpRequest();
	    xhr.onload=function(event)
	    {
	      if  ( ( xhr.status >= 200 && xhr.status < 300) || xhr.status == 304)   //上传成功
	      {
					var response = JSON.parse(xhr.response);
					alertMes(response.serviceResult,response.resultInfo);
          $scope.vat.photoAdress = response.resultParm.address;
	      }
	      else
	      {
	        alertMes(false,"图片上传失败，请重新尝试！");
	      }
	    };
			xhr.open("POST", addPhotoURL,true);
			xhr.send(formdata);
  }
  /******* 单条发票数据添加 end *************/


  //购买方
  $scope.$watch('selectIn',function(nv,ov) {
    if (ov!=nv) {
      if (nv=="clear") {
        $scope.vat.outCompany = null;
      }else {
        $http.get(getClientByIdURL,{params:{companyId:nv}})
        .success(function(res){
          $scope.vat.outCompany = res.resultParm.InCompany;
        })
        .error();
      }
    }
  });
  //销售方
  $scope.$watch('selectOut',function(nv,ov) {
    if (ov!=nv) {
      if (nv=="clear") {
        $scope.vat.inCompany = null;
      }else {
        $http.get(getProviderByIdURL,{params:{companyId:nv}})
        .success(function(res){
          $scope.vat.inCompany = res.resultParm.InCompany;
        })
        .error();
      }
    }
  });
  /***获取所有供应商和客户信息**/
  $http.get(getProviderURL)
    .success(function(res) {
      $scope.providers = res.resultParm.list;
  });
  $http.get(getClientURL)
    .success(function(res) {
      $scope.clients = res.resultParm.list;
  });
  /***获取所有商品大类别和小类别**/
  $scope.smallClass=[];
  $http.get(getLargeClassURL)
    .success(function(res){
      if (res.serviceResult) {
        $scope.largeClass=res.resultParm.LargeClass;
      }else {
        alertMes(res.serviceResult,res.resultInfo);
      }
    }).error(function(){
      alertMes('noHttp',null);
  });
  $scope.getSmallClass = function(id,i) {
    $http.get(getSmallClassURL,{
      params:{
        largeClassId:id
      }
    })
  		.success(function(res){
        if (res.serviceResult) {
          $scope.smallClass[i]=res.resultParm.smallClass;
        }else {
          alertMes(res.serviceResult,res.resultInfo);
        }
  		}).error(function(){
  			alertMes('noHttp',null);
  	});
  }
  $scope.lcSelChange = function(i){
    $scope.vat.listData[i].largeClassId = $scope.vat.listData[i].lcSel.largeClassId;
    $scope.vat.listData[i].taxRate = $scope.vat.listData[i].lcSel.largeClassVat;
    $scope.getSmallClass($scope.vat.listData[i].largeClassId,i);
  }
  $scope.scSelChange = function(i){
    $scope.vat.listData[i].smallClassId = $scope.vat.listData[i].scSel.smallClassId;
    $scope.caluator(i);
}



  $scope.rows=1;
  $scope.addRow = function(){
    var rowsIndex = $scope.rows;
    $scope.rows++;
    $(".addList").last().after(
       $compile(
      '<tr class="addList">'+
        '<td  colspan="2"><input type="text" name="commodityName" ng-model="vat.listData['+rowsIndex+'].commodityName"></td>'+
        '<td><select required ng-model="vat.listData['+rowsIndex+'].lcSel" ng-options="x.largeClassName for x in largeClass" ng-change="lcSelChange('+rowsIndex+')"></select></td>'+
        '<td><select required ng-model="vat.listData['+rowsIndex+'].scSel" ng-options="x.smallClassName for x in smallClass['+rowsIndex+']" ng-change="scSelChange('+rowsIndex+')"></select></td>'+
        '<td><input type="text" name="commodityType" ng-model="vat.listData['+rowsIndex+'].commodityType"></td>'+
        '<td ><input type="text" name="unit" ng-model="vat.listData['+rowsIndex+'].unit"></td>'+
        '<td><input type="number" name="commodityAmount" value="" ng-model="vat.listData['+rowsIndex+'].commodityAmount" ng-change="caluator('+rowsIndex+')"/></td>'+
        '<td><input type="number" name="price" value="" ng-model="vat.listData['+rowsIndex+'].price" ng-change="caluator('+rowsIndex+')"/></td>'+
        '<td><input type="number" name="allPrice" value="" ng-model="vat.listData['+rowsIndex+'].allPrice" ng-change="caluator('+rowsIndex+')"/></td>'+
        '<td><input type="number" name="taxRate" value="" ng-model="vat.listData['+rowsIndex+'].taxRate" ng-change="caluator('+rowsIndex+')"/></td>'+
        '<td><input type="number" name="vatMoney" value="" ng-model="vat.listData['+rowsIndex+'].vatMoney" ng-change="caluator('+rowsIndex+')"/></td>'+
      '</tr>')($scope)
    );
  }
  //自动计算金额（单价*数量），税额（金额*税率），金额合计，税额合计，价税合计
  $scope.caluator = function(i){
    $scope.vat.listData[i].allPrice = $scope.vat.listData[i].price*$scope.vat.listData[i].commodityAmount;
    $scope.vat.listData[i].vatMoney = $scope.vat.listData[i].taxRate*$scope.vat.listData[i].allPrice;
    $scope.vat.price =0;$scope.vat.vatMoney=0;
    for (var m = 0; m < $scope.vat.listData.length; m++) {
      $scope.vat.price += $scope.vat.listData[m].allPrice;
      $scope.vat.vatMoney += $scope.vat.listData[m].vatMoney;
    }
    $scope.vat.allPrice = $scope.vat.price+$scope.vat.vatMoney;
  }
});
